package com.woniuxy.gateway.util;

import com.woniuxy.redis.util.RedisUtil;
import io.jsonwebtoken.Claims;
import io.jsonwebtoken.Jwts;
import io.jsonwebtoken.security.Keys;

import java.security.Key;
import java.util.Date;
import java.util.Map;

/**
 * 工具类
 */

public class JWTUtil {
    static String userSect ="sjcdiyvhalhxyajlsjvgdoplmcqjfsoa";
    static String adminSect ="ksaasfdasdfadsfwfrasdfsadffcasijfasadfasfdlkfjlasjflksajfd";

    /**
     * 生成用户token
     * @param body
     * @param mil
     * @return
     */
    public static String createUserToken(Map<String, Object> body, Integer mil) {
        Key key = Keys.hmacShaKeyFor(userSect.getBytes());
        return Jwts.builder()
                .setClaims(body)
                .setExpiration(new Date(System.currentTimeMillis() + mil * 60 * 1000))
                .signWith(key)
                .compact();
    }

    /**
     * 解析用户token
     * @param token
     * @return
     */
    public static Claims parseUserToken(String token) {
        Key key = Keys.hmacShaKeyFor(userSect.getBytes());
        return Jwts.parserBuilder().setSigningKey(key)
                .build().parseClaimsJws(token).getBody();
    }

    /**
     * 生成管理员token
     * @param body
     * @param mil
     * @return
     */
    public static String createAdminToken(Map<String, Object> body, Integer mil) {
        Key key = Keys.hmacShaKeyFor(adminSect.getBytes());
        return Jwts.builder()
                .setClaims(body)
                .setExpiration(new Date(System.currentTimeMillis() + mil * 60 * 1000))
                .signWith(key)
                .compact();
    }

    /**
     * 解析管理员token
     * @param token
     * @return
     */
    public static Claims parseAdminToken(String token) {
        Key key = Keys.hmacShaKeyFor(adminSect.getBytes());
        return Jwts.parserBuilder().setSigningKey(key)
                .build().parseClaimsJws(token).getBody();
    }

    /**
     * token  JWT获取账号id
     * @param token
     * @return
     */
    public static Integer getAccountId(String token){
        RedisUtil redisUtil=new RedisUtil();
        String refreshToken = redisUtil.get(token);
        int accountId = Integer.parseInt(JWTUtil.parseAdminToken(refreshToken).get("accountId").toString());
        return accountId;
    }
}
